"""
演示脚本 - 展示系统核心功能（不需要API Key）
这个脚本展示了插槽填充和服务管理的基础功能
"""
from slots import BookingSlots, IntentType, ServiceType, SlotFiller
from service_manager import ServiceManager


def print_section(title):
    """打印分隔线"""
    print("\n" + "=" * 60)
    print(f"  {title}")
    print("=" * 60 + "\n")


def demo_slot_management():
    """演示插槽管理"""
    print_section("演示1: 插槽管理系统")
    
    # 创建空插槽
    slots = BookingSlots()
    print("创建新的预定插槽...")
    print(f"初始状态 - 是否完整: {slots.is_complete()}")
    print(f"缺失插槽: {slots.get_missing_slots()}\n")
    
    # 设置意图
    slots.intent = IntentType.BOOK
    print(f"设置意图: {slots.intent.value}")
    print(f"必需插槽: {slots.get_required_slots()}\n")
    
    # 逐步填充插槽
    print("开始填充插槽...")
    slots.student_name = "张三"
    print(f"✓ 填充学生姓名: {slots.student_name}")
    print(f"  剩余缺失: {slots.get_missing_slots()}\n")
    
    slots.service_type = ServiceType.HOMEWORK_TUTORING
    print(f"✓ 填充服务类型: {slots.service_type.value}")
    print(f"  剩余缺失: {slots.get_missing_slots()}\n")
    
    slots.date = "2024-01-15"
    print(f"✓ 填充日期: {slots.date}")
    print(f"  剩余缺失: {slots.get_missing_slots()}\n")
    
    slots.time_slot = "14:00-16:00"
    print(f"✓ 填充时间段: {slots.time_slot}")
    print(f"  剩余缺失: {slots.get_missing_slots()}\n")
    
    print(f"插槽填充完成！完整性: {slots.is_complete()}")
    print("\n完整信息:")
    print(slots)


def demo_intent_recognition():
    """演示意图识别"""
    print_section("演示2: 意图识别")
    
    filler = SlotFiller()
    
    test_cases = [
        ("我想预定作业辅导", IntentType.BOOK),
        ("取消我的预定", IntentType.CANCEL),
        ("查询我的预定", IntentType.QUERY),
        ("查看所有预定", IntentType.LIST_ALL),
        ("帮我报名体育活动", IntentType.BOOK),
    ]
    
    for user_input, expected in test_cases:
        intent = filler.extract_intent(user_input)
        status = "✓" if intent == expected else "✗"
        print(f"{status} '{user_input}'")
        print(f"   识别为: {intent.value} (期望: {expected.value})\n")


def demo_service_extraction():
    """演示服务类型提取"""
    print_section("演示3: 服务类型提取")
    
    filler = SlotFiller()
    
    test_cases = [
        "我想要作业辅导",
        "报名数学辅导",
        "预定体育活动",
        "参加艺术课程",
        "上兴趣班",
    ]
    
    for user_input in test_cases:
        service = filler.extract_service_type(user_input)
        print(f"'{user_input}'")
        print(f"  → {service.value if service else '未识别'}\n")


def demo_booking_workflow():
    """演示完整的预定工作流"""
    print_section("演示4: 完整预定流程")
    
    manager = ServiceManager()
    
    # 创建多个预定
    print("创建预定记录...\n")
    
    bookings_data = [
        ("张三", ServiceType.HOMEWORK_TUTORING, "2024-01-15", "14:00-16:00"),
        ("李四", ServiceType.SPORTS_ACTIVITY, "2024-01-15", "16:00-18:00"),
        ("王五", ServiceType.ART_CLASS, "2024-01-16", "14:00-16:00"),
    ]
    
    booking_ids = []
    
    for student, service, date, time in bookings_data:
        slots = BookingSlots()
        slots.intent = IntentType.BOOK
        slots.student_name = student
        slots.service_type = service
        slots.date = date
        slots.time_slot = time
        slots.confirmed = True
        
        success, message, booking = manager.create_booking(slots)
        if success:
            print(f"✓ {student} - {service.value} ({date} {time})")
            print(f"  预定编号: {booking.booking_id}\n")
            booking_ids.append(booking.booking_id)
        else:
            print(f"✗ 创建失败: {message}\n")
    
    # 查询预定
    print("\n查询张三的预定...")
    success, message, bookings = manager.query_bookings("张三")
    print(f"结果: 找到 {len(bookings)} 条预定\n")
    
    # 列出所有预定
    print("列出所有预定...")
    success, message, all_bookings = manager.list_all_bookings()
    print(f"结果: 共有 {len(all_bookings)} 条有效预定\n")
    
    # 取消一个预定
    if booking_ids:
        cancel_id = booking_ids[0]
        print(f"取消预定 {cancel_id}...")
        success, message = manager.cancel_booking(cancel_id)
        print(f"结果: {'成功' if success else '失败'}\n")
    
    # 再次查询
    print("取消后再次查询张三的预定...")
    success, message, bookings = manager.query_bookings("张三")
    print(f"结果: 找到 {len(bookings)} 条有效预定")


def demo_conflict_detection():
    """演示时间冲突检测"""
    print_section("演示5: 时间冲突检测")
    
    manager = ServiceManager()
    
    # 创建第一个预定
    print("创建第一个预定：张三 - 作业辅导 (2024-01-15 14:00-16:00)")
    slots1 = BookingSlots()
    slots1.intent = IntentType.BOOK
    slots1.student_name = "张三"
    slots1.service_type = ServiceType.HOMEWORK_TUTORING
    slots1.date = "2024-01-15"
    slots1.time_slot = "14:00-16:00"
    slots1.confirmed = True
    
    success, message, booking1 = manager.create_booking(slots1)
    print(f"结果: {'✓ 成功' if success else '✗ 失败'}\n")
    
    # 尝试创建冲突预定（相同服务、时间）
    print("尝试创建冲突预定：李四 - 作业辅导 (2024-01-15 14:00-16:00)")
    slots2 = BookingSlots()
    slots2.intent = IntentType.BOOK
    slots2.student_name = "李四"
    slots2.service_type = ServiceType.HOMEWORK_TUTORING
    slots2.date = "2024-01-15"
    slots2.time_slot = "14:00-16:00"
    slots2.confirmed = True
    
    success, message, booking2 = manager.create_booking(slots2)
    print(f"结果: {'✗ 被阻止（预期）' if not success else '✓ 意外成功'}")
    print(f"原因: {message}\n")
    
    # 创建不冲突的预定
    print("创建不冲突预定：李四 - 作业辅导 (2024-01-15 16:00-18:00)")
    slots3 = BookingSlots()
    slots3.intent = IntentType.BOOK
    slots3.student_name = "李四"
    slots3.service_type = ServiceType.HOMEWORK_TUTORING
    slots3.date = "2024-01-15"
    slots3.time_slot = "16:00-18:00"
    slots3.confirmed = True
    
    success, message, booking3 = manager.create_booking(slots3)
    print(f"结果: {'✓ 成功' if success else '✗ 失败'}")


def demo_statistics():
    """演示统计功能"""
    print_section("演示6: 统计信息")
    
    manager = ServiceManager()
    
    # 创建一些测试数据
    test_data = [
        ("张三", ServiceType.HOMEWORK_TUTORING, "2024-01-15", "14:00-16:00"),
        ("李四", ServiceType.HOMEWORK_TUTORING, "2024-01-15", "16:00-18:00"),
        ("王五", ServiceType.SPORTS_ACTIVITY, "2024-01-16", "14:00-16:00"),
        ("赵六", ServiceType.ART_CLASS, "2024-01-16", "16:00-18:00"),
    ]
    
    for student, service, date, time in test_data:
        slots = BookingSlots()
        slots.intent = IntentType.BOOK
        slots.student_name = student
        slots.service_type = service
        slots.date = date
        slots.time_slot = time
        slots.confirmed = True
        manager.create_booking(slots)
    
    # 获取统计信息
    stats = manager.get_statistics()
    
    print("预定统计:")
    print(f"  总预定数: {stats['total_bookings']}")
    print(f"  有效预定: {stats['active_bookings']}")
    print(f"  已取消: {stats['cancelled_bookings']}\n")
    
    print("服务类型分布:")
    for service_type, count in stats['service_type_distribution'].items():
        print(f"  {service_type}: {count} 次")


def main():
    """主函数"""
    print("\n")
    print("🎓" * 30)
    print(" " * 20 + "智能课后服务Agent - 核心功能演示")
    print("🎓" * 30)
    print("\n这个演示展示了系统的核心功能，无需API Key即可运行\n")
    
    try:
        # 运行各个演示
        demo_slot_management()
        input("\n按回车继续...")
        
        demo_intent_recognition()
        input("\n按回车继续...")
        
        demo_service_extraction()
        input("\n按回车继续...")
        
        demo_booking_workflow()
        input("\n按回车继续...")
        
        demo_conflict_detection()
        input("\n按回车继续...")
        
        demo_statistics()
        
        print("\n" + "=" * 60)
        print("  演示完成！")
        print("=" * 60)
        print("\n💡 提示:")
        print("  - 运行 'python test_basic.py' 进行完整测试")
        print("  - 运行 'python main.py' 启动交互式助手（需要API Key）")
        print("  - 查看 README.md 了解更多信息\n")
        
    except KeyboardInterrupt:
        print("\n\n演示已中断")
    except Exception as e:
        print(f"\n发生错误: {e}")
        import traceback
        traceback.print_exc()


if __name__ == "__main__":
    main()
